local H = require "packages/new_heg/util"
local U = require "packages/utility/utility"
local extension = Package:new("tenyear_diy_heg")
extension.extensionName = "hegemony_diy"
extension.game_modes_whitelist = { 'nos_heg_mode', 'new_heg_mode' }

Fk:loadTranslationTable{
  ["tenyear_diy_heg"] = "国战-十周年",
}

local duyu = General(extension, "ty_heg__duyu", "wei", 3)
local jianguo = fk.CreateActiveSkill{
  name = "ty_heg__jianguo",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#jianguo",
  interaction = function(self)
    return UI.ComboBox { choices = {"jianguo1", "jianguo2"} }
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    if self.interaction.data == "jianguo1" then
      return #selected == 0
    elseif self.interaction.data == "jianguo2" then
      return #selected == 0 and not Fk:currentRoom():getPlayerById(to_select):isNude()
    end
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    if self.interaction.data == "jianguo1" then
      target:drawCards(1, self.name)
      if not target.dead and target:getHandcardNum() > 1 then
        local n = target:getHandcardNum() // 2
        room:askForDiscard(target, math.min(5, n), math.min(5, n), false, self.name, false)
      end
    else
      room:askForDiscard(target, 1, 1, true, self.name, false)
      if not target.dead and target:getHandcardNum() > 1 then
        local n = target:getHandcardNum() // 2
        target:drawCards(math.min(5, n), self.name)
      end
    end
  end,
}
local qingshid = fk.CreateTriggerSkill{
  name = "ty_heg__qingshid",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e) 
      local use = e.data[1]
      return use.from == player.id
    end, Player.HistoryTurn)
    return target == player and player:hasSkill(self) and player.phase ~= Player.NotActive and
      player:getHandcardNum() == #events and player:getHandcardNum() <= 5 and
      data.tos and data.firstTarget and table.find(AimGroup:getAllTargets(data.tos), function(id) return id ~= player.id end)
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, AimGroup:getAllTargets(data.tos), 1, 1, "#qingshid-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:damage{
      from = player,
      to = player.room:getPlayerById(self.cost_data),
      damage = 1,
      skillName = self.name,
    }
  end,
}

duyu:addCompanions("ty_heg__yanghu")
duyu:addSkill(jianguo)
duyu:addSkill(qingshid)
Fk:loadTranslationTable{
  ["ty_heg__duyu"] = "杜预",
  ["#ty_heg__duyu"] = "文成武德",
  ["designer:ty_heg__duyu"] = "歪歪",
  ["illustrator:ty_heg__duyu"] = "君桓文化",

  ["ty_heg__jianguo"] = "谏国",
  [":ty_heg__jianguo"] = "出牌阶段限一次，你可选择一项：1. 令一名角色摸一张牌，然后弃置半数手牌；"..
  "2. 令一名角色弃置一张牌，然后摸半数手牌数量的牌。（均向下取整且至多为5）",
  ["ty_heg__qingshid"] = "倾势",
  [":ty_heg__qingshid"] = "当你于回合内使用【杀】或锦囊牌指定其他角色为目标后，若此牌是你本回合使用的第X张牌（X为你的手牌数且至多为5），你可以对其中一名目标角色造成1点伤害。",


  ["jianguo1"] = "摸一张牌，弃置半数手牌",
  ["jianguo2"] = "弃置一张牌，摸半数手牌",
  ["#qingshid-choose"] = "倾势：你可以对其中一名角色造成1点伤害",

  ["$ty_heg__jianguo1"] = "彭蠡雁惊，此诚平吴之时。",
  ["$ty_heg__jianguo2"] = "奏三陈之诏，谏一国之弊。",
  ["$ty_heg__qingshid1"] = "潮起万丈之仞，可阻江南春风。",
  ["$ty_heg__qingshid2"] = "缮甲兵，耀威武，伐吴指日可待。",
  ["~ty_heg__duyu"] = "六合即归一统，奈何寿数已尽……",
}

local xianglang = General(extension, "ty_heg__xianglang", "shu", 3)
local kanji = fk.CreateActiveSkill{
  name = "ty_heg__kanji",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local cards = player.player_cards[Player.Hand]
    player:showCards(cards)
    local suits = {}
    for _, id in ipairs(cards) do
      local suit = Fk:getCardById(id).suit
      if suit ~= Card.NoSuit then
        if table.contains(suits, suit) then
          return
        else
          table.insert(suits, suit)
        end
      end
    end
    local suits1 = #suits
    player:drawCards(2, self.name)
    if suits1 == 4 then return end
    suits = {}
    for _, id in ipairs(player.player_cards[Player.Hand]) do
      local suit = Fk:getCardById(id).suit
      if suit ~= Card.NoSuit then
        table.insertIfNeed(suits, suit)
      end
    end
    if #suits == 4 then
      player.room:addPlayerMark(player, MarkEnum.AddMaxCardsInTurn, 2)
    else
      room:askForDiscard(player, 2, 2, true, self.name, false)
    end
  end,
}

local qianzheng = fk.CreateTriggerSkill{
  name = "ty_heg__qianzheng",
  anim_type = "drawcard",
  events = {fk.TargetConfirming},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from ~= player.id and
      (data.card:isCommonTrick() or data.card.trueName == "slash") and #player:getCardIds{Player.Hand, Player.Equip} > 1 and
      player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local prompt = "#ty_heg__qianzheng1-card:::"..data.card:getTypeString()..":"..data.card:toLogString()
    if data.card:isVirtual() and not data.card:getEffectiveId() then
      prompt = "#ty_heg__qianzheng2-card"
    end
    local cards = player.room:askForCard(player, 2, 2, true, self.name, true, ".", prompt)
    if #cards == 2 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = self.cost_data
    local card1 = Fk:getCardById(cards[1])
    local card2 = Fk:getCardById(cards[2])
    if card1.type ~= data.card.type and card2.type ~= data.card.type and card1.type ~= card2.type then
      data.extra_data = data.extra_data or {}
      data.extra_data.qianzheng = player.id
    else
      data.disresponsiveList = data.disresponsiveList or {}
      table.insertIfNeed(data.disresponsiveList, player.id)
    end
    room:recastCard(cards, player, self.name)
  end,
}
local qianzheng_trigger = fk.CreateTriggerSkill{
  name = "#ty_heg__qianzheng_trigger",
  mute = true,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return data.extra_data and data.extra_data.qianzheng and data.extra_data.qianzheng == player.id and
      player.room:getCardArea(data.card) == Card.Processing and not player.dead
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, "ty_heg__qianzheng", nil, "#ty_heg__qianzheng-invoke:::"..data.card:toLogString())
  end,
  on_use = function(self, event, target, player, data)
    player.room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
  end,
}

qianzheng:addRelatedSkill(qianzheng_trigger)
xianglang:addCompanions("ld__masu")
xianglang:addSkill(kanji)
xianglang:addSkill(qianzheng)
Fk:loadTranslationTable{
  ["ty_heg__xianglang"] = "向朗",
  ["#ty_heg__xianglang"] = "校书翾翻",
  ["designer:ty_heg__xianglang"] = "佚名",
  ["illustrator:ty_heg__xianglang"] = "匠人绘",

  ["ty_heg__kanji"] = "勘集",
  [":ty_heg__kanji"] = "出牌阶段限一次，你可展示所有手牌，若花色均不同，你摸两张牌，若因此使手牌包含四种花色，你本回合手牌上限+2，若你手牌不包含四种花色，你弃置两张牌。",
  ["ty_heg__qianzheng"] = "愆正",
  [":ty_heg__qianzheng"] = "每回合限一次，当你成为其他角色使用普通锦囊牌或【杀】的目标时，你可重铸两张牌，若这两张牌：与使用牌共包含三种类型，"..
  "此牌结算后进入弃牌堆时你可以获得之，否则你不能响应此牌。",
  ["#ty_heg__qianzheng1-card"] = "愆正：你可以重铸两张牌，若均不为%arg，结算后获得%arg2，否则你不能响应此牌。",
  ["#ty_heg__qianzheng2-card"] = "愆正：你可以重铸两张牌",
  ["#ty_heg__qianzheng-invoke"] = "愆正：你可以获得此%arg",

  ["$ty_heg__kanji1"] = "览文库全书，筑文心文胆。",
  ["$ty_heg__kanji2"] = "世间学问，皆载韦编之上。",
  ["$ty_heg__qianzheng1"] = "悔往昔之种种，恨彼时之切切。",
  ["$ty_heg__qianzheng2"] = "罪臣怀咎难辞，有愧国恩。",
  ["~ty_heg__xianglang"] = "识文重义而徇私，恨也……",
}

local tengyin = General(extension, "ty_heg__tengyin", "wu", 3)
local chenjian = fk.CreateTriggerSkill{
  name = "ty_heg__chenjian",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local num = math.max(#player.player_cards[Player.Equip], 1)
    local ids = room:getNCards(num)
    room:moveCards({
      ids = ids,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = self.name,
    })
    local choices = {"chenjian1", "chenjian2", "Cancel"}
    local choice = U.askforViewCardsAndChoice(player, ids, choices, self.name, "#ty_heg__chenjian-ask")
    ids = table.filter(ids, function(id) return room:getCardArea(id) == Card.Processing end)
    if choice == "chenjian1" then
      local suits = {}
      for _, id in ipairs(ids) do
        table.insertIfNeed(suits, Fk:getCardById(id):getSuitString())
      end
      local to, c = room:askForChooseCardAndPlayers(player, table.map(player.room.alive_players, Util.IdMapper), 1, 1, ".|.|"..table.concat(suits, ","), "#chenjian-choose", self.name, true)
      if #to > 0 and c then
        local card = Fk:getCardById(c)
        room:throwCard({c}, self.name, player, player)
        if room:getPlayerById(to[1]).dead then return end
        local to_get = {}
        for i = #ids, 1, -1 do
          if card:compareSuitWith(Fk:getCardById(ids[i])) then
            table.insert(to_get, ids[i])
            table.removeOne(ids, ids[i])
          end
        end
        room:obtainCard(to[1], to_get, true, fk.ReasonJustMove)
      end
    elseif choice == "chenjian2" then
      room:setPlayerMark(player, "chenjian_view", table.simpleClone(ids))
      local availableCards = {}
      for _, id in ipairs(ids) do
        local card = Fk:getCardById(id)
        if not player:prohibitUse(card) and card.skill:canUse(player, card) then
          table.insertIfNeed(availableCards, id)
        end
      end
      room:setPlayerMark(player, "chenjian_cards", availableCards)
      local success, dat = room:askForUseActiveSkill(player, "ty_heg__chenjian_viewas", "#chenjian-use", true, { bypass_times = true })
      room:setPlayerMark(player, "chenjian_view", 0)
      room:setPlayerMark(player, "chenjian_cards", 0)
      if success then
        local card = Fk:getCardById(dat.cards[1])
        room:useCard{
          from = player.id,
          tos = table.map(dat.targets, function(id) return {id} end),
          card = card,
          extraUse = true,
        }
      end
    end

    ids = table.filter(ids, function(id) return room:getCardArea(id) == Card.Processing end)
    if #ids > 0 then
      room:moveCards({
        ids = ids,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
      })
    end
  end,
}
local chenjian_viewas = fk.CreateViewAsSkill{
  name = "ty_heg__chenjian_viewas",
  expand_pile = function(self)
    -- return U.getMark(Self, "chenjian_view")
    return Self:getTableMark("chenjian_view")
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      local ids = Self:getMark("chenjian_cards")
      return type(ids) == "table" and table.contains(ids, to_select)
    end
  end,
  view_as = function(self, cards)
    if #cards == 1 then
      return Fk:getCardById(cards[1])
    end
  end,
}
local xixiu = fk.CreateTriggerSkill{
  name = "ty_heg__xixiu",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetConfirmed, fk.BeforeCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.TargetConfirmed then
      return target == player and data.from ~= player.id and
        table.find(player:getCardIds("e"), function(id) return Fk:getCardById(id).suit == data.card.suit end) and player:getMark("ty_heg__xixiu-turn") == 0
    else
      if #player:getCardIds("e") ~= 1 then return end
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.proposer ~= player.id and move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.TargetConfirmed then
      player:drawCards(1, self.name)
      player.room:setPlayerMark(player, "ty_heg__xixiu-turn", 1)
    else
      local ids = {}
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.proposer ~= player.id and move.toArea == Card.DiscardPile then
          local move_info = {}
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip then
              table.insert(ids, info.cardId)
            else
              table.insert(move_info, info)
            end
          end
          if #ids > 0 then
            move.moveInfo = move_info
          end
        end
      end
      if #ids > 0 then
        player.room:sendLog{
          type = "#cancelDismantle",
          card = ids,
          arg = self.name,
        }
      end
    end
  end,
}
Fk:addSkill(chenjian_viewas)
tengyin:addSkill(chenjian)
tengyin:addSkill(xixiu)
Fk:loadTranslationTable{
  ["ty_heg__tengyin"] = "滕胤",
  ["#ty_heg__tengyin"] = "厉操遵蹈",
  ["designer:ty_heg__tengyin"] = "步穗",
  ["illustrator:ty_heg__tengyin"] = "猎枭",

  ["ty_heg__chenjian"] = "陈见",
  [":ty_heg__chenjian"] = "准备阶段，你可亮出牌堆顶的X张牌并可选择一项：1.弃置一张牌，令一名角色获得其中此牌花色的牌；2.使用其中一张牌。（X为你装备区内牌数且至少为1）",
  ["ty_heg__xixiu"] = "皙秀",
  [":ty_heg__xixiu"] = "锁定技，①每回合限一次，当你成为其他角色使用牌的目标后，若你装备区内有与此牌花色相同的牌，你摸一张牌；②其他角色弃置你装备区内的最后一张牌时，取消之。",

  ["#ty_heg__chenjian-ask"] = "陈见：请选择一项",
  ["ty_heg__chenjian_viewas"] = "陈见",

  ["chenjian1"] = "弃置牌，令一名角色获得同花色的牌",
  ["chenjian2"] = "使用其中一张牌",

  ["$ty_heg__chenjian1"] = "国有其弊，上书当陈。",
  ["$ty_heg__chenjian2"] = "食君之禄，怎可默言。",
  ["$ty_heg__xixiu1"] = "君子如玉，德形皓白。",
  ["$ty_heg__xixiu2"] = "木秀于身，芬芳自如。",
  ["~ty_heg__tengyin"] = "臣好洁，不堪与之合污！",
}

return extension
